from rest_framework.response import Response
from rest_framework.views import APIView
from django0924.settings import EMAIL_HOST_USER, SECRET_KEY
from .sers import *
from django.core.mail import send_mail
from django.contrib.auth.hashers import check_password
import jwt
import datetime


# 注册视图
class RegisterView(APIView):
    def post(self, request):
        # 获取传递过来的数据，传递给序列号器
        ser = RegisterSerializers(data=request.data)
        if ser.is_valid():
            user = ser.save()
            # 发送邮件去激活账户
            send_mail("积云激活邮件", "", EMAIL_HOST_USER, recipient_list=[request.data.get("email")],
                      html_message="H1912A班发来贺电:恭喜您！，注册成功，接下来请激活账号<a href='http://127.0.0.1:8000/active?id={}'>激活</a>".
                      format(user.id))
            return Response({"msg": "注册成功", "code": 200})
        else:
            print(ser.errors)
            return Response({"msg": "注册失败", "code": 400, "error": ser.errors})


class UserView(APIView):
    def get(self, request):
        # 获取传递来的数据，传递给序列号器
        username = request.GET.get("username")
        if User.objects.filter(username=username):
            return Response({"msg": "用户名已经存在 ", "code": 400})
        else:
            return Response({"msg": "用户名可用 ", "code": 200})


class UserActiveView(APIView):
    def get(self, request):
        # 修改一个用户的 状态
        id = request.GET.get("id")
        # 修改 用户的状态为2
        User.objects.filter(id=id).update(status=2)

        return Response({"msg": "激活成功"})


class LoginView(APIView):

    def post(self, request):
        username = request.data.get("username")
        password = request.data.get("password")

        user = User.objects.filter(username=username).first()
        if user and check_password(password, user.password):
            payload = {
                "exp": datetime.datetime.utcnow() + datetime.timedelta(minutes=2),
                "uid": user.id
            }
            # 先验证用户名 在验证密码
            token = jwt.encode(payload, SECRET_KEY)
            return Response({"msg": "登录成功", "status": 200, "token": token})
        else:
            return Response({"msg": "登录失败", "status": 400})


class TestTokenView(APIView):
    def get(self, request):
        token = request.GET.get('token')
        print(token)
        # 对 token 进行解码
        try:
            data = jwt.decode(token, SECRET_KEY)
        except Exception as e:
            print(e)
            return Response({"msg": "没有登录或登陆失效请重新登录"})
        #  data 解码为字典
        uid = data['uid']
        user = User.objects.get(id=uid)

        return Response({'msg': '识别出%s登录，欢迎你' % user.username})
